#include <stdio.h>
#include <string.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_error.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_rect.h>

#include "display.h"

extern int width;
extern int height;
int screenWidth = 0;
int screenHeight = 0;
char *cells = NULL;
SDL_Window *window = NULL;
SDL_Renderer* renderer = NULL;
int flag = 0;//1 for qiut
int pause = 1;// 0 for pause
int steps = 999;

void menu(){
    int choice = 4;
    do{
        printf("Please choose an option:\n1.A new game\n2.Continue last game\n3.Select demo\n");
        scanf("%d", &choice);
        switch(choice){
            case 1:
                {
                    int w,h;
                    printf("Please enter the width:");
                    scanf("%d", &w);
                    printf("Please enter the height:");
                    scanf("%d", &h);
                    cells = createNewGrid(w, h);
                    break;
                }
            case 2:
                load();
                break;
            case 3:
                {
                    int demo = 4;
                    do{
                        printf("Please choose an option:\n1.demo 1\n2.demo 2\n3.demo 3\n");
                        scanf("%d", &demo);
                        switch(demo){
                            case 1:
                                example1();
                                break;
                            case 2:
                                example2();
                                break;
                            case 3:
                                example3();
                                break;
                            default:
                                printf("Please choose option above.\n");
                                break;
                        }
                    }while(demo != 1 && demo != 2 && demo != 3);
                    break;
                }
            default:
                printf("Please choose option above.\n");
                break;
        }
    }while(choice != 1 && choice != 2 && choice != 3);

    return;
}

void step(){
  int choice = 3;
  do{
      printf("Please choose an option:\n1.Set steps\n2.No setting\n");
      scanf("%d", &choice);
      switch(choice){
          case 1:
          {
            printf("Please enter steps:");
            scanf("%d", &steps);
          }
          break;
          case 2:
          break;
          default:
          printf("Please choose option above.\n");
          break;
      }
    }while(choice != 1 && choice != 2);
}

void init(){

    screenWidth = width * SIZE;
    screenHeight = height * SIZE;

    if (SDL_Init(SDL_INIT_VIDEO) != 0)
        fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());

    atexit(SDL_Quit); // set for clean-up on exit

    SDL_CreateWindowAndRenderer(screenWidth, screenHeight, 0, &window, &renderer);
    SDL_SetWindowTitle( window, WINDOW_TITLE);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    return;
}

void display(){
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);

    for(int j = 0; j < height; j++) // Loop through each cell in the grid and draw
    {
        for(int i = 0; i < width; i++)
        {
            SDL_Rect rect = {i*SIZE, j*SIZE, SIZE, SIZE};

            if(cells[i+j*width] == '0') // If cell is dead, draw color based on when last alive to show as trail
            {
                SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
            } else {
                SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            }
            SDL_RenderFillRect(renderer, &rect);
        }
    }

    SDL_RenderPresent(renderer);
}

void quit(){
    store();
    if (renderer){
        SDL_DestroyRenderer(renderer);
    }
    if (window){
        SDL_DestroyWindow(window);
    }
    SDL_Quit();
}

void input(){
    SDL_Event event;

    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_QUIT) // If top-right X is clicked, quit game
        {
            flag = 1;
            break;
        }

        else if (event.type == SDL_MOUSEBUTTONDOWN) // Handle mouse input - click any mouse button to flip alive/dead status
        {
            int x, y;
            SDL_GetMouseState(&x, &y);

            int gridX, gridY; // Convert mouse x/y co-ords to grid numbers
            gridX = x / SIZE;
            gridY = y / SIZE;

            if(cells[gridX+gridY*width] == 1) // Flip dead to alive and alive to dead
                changeCell(cells, gridX, gridY, '0');
            else
                changeCell(cells, gridX, gridY, '1');
        }

        if(event.type == SDL_KEYDOWN) // Handle keyboard input
        {
            if(event.key.keysym.sym == SDLK_SPACE) // Press Space to pause/unpause
            {
                if(pause)
                    pause = 0;
                else
                    pause = 1;

            }
        }
    }
}

void nextstep(){
    cells = changeGrid(cells);
}

void example1()
{
    cells = createNewGrid(50, 50);
    changeCell(cells, 30, 20, '1');
    changeCell(cells, 31, 20, '1');
    changeCell(cells, 32, 20, '1');
    changeCell(cells, 30, 21, '1');
    changeCell(cells, 31, 22, '1');
}
void example2()
{
    cells = createNewGrid(50, 50);
    changeCell(cells, 30, 20, '1');
    changeCell(cells, 31, 20, '1');
    changeCell(cells, 31, 21, '1');
    changeCell(cells, 30, 21, '1');
}
void example3()
{
    cells = createNewGrid(50, 50);
    changeCell(cells, 20, 20, '1');
    changeCell(cells, 21, 20, '1');
    changeCell(cells, 22, 20, '1');
    changeCell(cells, 19, 21, '1');
    changeCell(cells, 20, 21, '1');
    changeCell(cells, 21, 21, '1');
}

void load(){
    FILE *fp;
    char buf[100];
	fp = fopen("last.txt", "r");
	if (!fp) {
		fprintf(stderr, "Failed in opening %s\n", "last.txt");
	}
  int w,h;
  fgets(buf, 100, fp);
		sscanf(buf,"%d\n",&w);
    width = w;
    fgets(buf, 100, fp);
  		sscanf(buf,"%d\n",&h);
      height = h;
    cells = (char*)calloc(w*h,sizeof(char));
    char *str = (char*)calloc(w,sizeof(char));
    for(int j=0; j<h;j++)
        {
          fgets(buf, 100, fp);
            sscanf(buf,"%s\n",str);
            strcat(cells, str);
      }
    fclose(fp);
}

//store data
//return 0 if successfully, otherwise return 1 and error information
void store(){
    FILE *fp;
	fp = fopen("last.txt", "w+");
	if (!fp) {
		fprintf(stderr, "Failed in opening %s\n", "last.txt");
	}
	fprintf(fp, "%d\n", width);
    fprintf(fp, "%d\n", height);
for(int j=0; j<height;j++)
    {
      for(int i=0; i<width; i++)
    fprintf(fp, "%c", cells[i+j*width]);
    fprintf(fp, "\n");
  }
    fclose(fp);
}
